'use strict';

angular.module('afasApp')
  .controller('CitiesCtrl', ['$scope', '$state', 'Services', function ($scope, $state, Services) {

    $scope.cities = [];
    $scope.provinces = [];
    $scope.countries = [];
    $scope.cityNew = {};
    $scope.errors = {};

    // PAGING SECTION
    // $scope.pagesize = 5;
    // $scope.pagination = {
    //   current: 1
    // };
    // $scope.pageChanged = function(newPage) {
    //   getResultsPage(newPage);
    // };
    // function getResultsPage(pageNumber) {
    //   var data = {
    //     pagesize: $scope.pagesize,
    //     page: (pageNumber - 1)
    //   };
    //   Services.getItems('cities', data)
    //   .then(function( results ) {
    //     console.log(results);
    //     var pagingData = angular.fromJson(results.headers['x-pagination']);
    //     $scope.totalItems = pagingData.TotalCount;
    //     $scope.cities = results.data;
    //   });
    // }
    // getResultsPage(1);

    // Services.getItems
    Services.getItems('cities')
    .then(function( results ) {
      console.log(results);
      $scope.cities = results.data;
    });

    Services.getItems('provinces')
    .then(function(results){
      $scope.provinces = results.data;
    });

    $scope.addCity = function () {
      $scope.errors = {};
      Services.add('cities', $scope.cityNew)
      .then(function(results){
        console.log(results);
        $scope.cityNew = {};
        $state.go( 'cities.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.deleteCity = function (city) {
      Services.delete('cities', city);
    };
  }]).controller('CityCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.currentCity = {};
    $scope.currentID = $stateParams.id;

    Services.getItems('provinces')
    .then(function(results){
      $scope.provinces = results.data;
    });

    Services.getItem('cities', $stateParams.id)
    .then(function(results){
      $scope.currentCity = results.data;
    });

    $scope.updateCity = function () {
      Services.update('cities', $scope.currentCity, $scope.currentID)
      .then(function(results){
        $state.go( 'cities.show', {id: $scope.currentID} );
      });
    };
  }]);